package com.hangzhou.xyj.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.hangzhou.xyj.R;
import com.hangzhou.xyj.XYJApplication;
import com.hangzhou.xyj.engine.BaiduMapLocationEngine;
import com.hangzhou.xyj.event.LocationRespEvent;
import com.hangzhou.xyj.event.OperationRespEvent;
import com.hangzhou.xyj.event.base.EventCode;
import com.hangzhou.xyj.manager.IntentManager;
import com.hangzhou.xyj.model.ImageModel;
import com.hangzhou.xyj.model.type.EIntentTagType;
import com.hangzhou.xyj.net.handler.AddDynamicHandler;
import com.hangzhou.xyj.net.http.HttpLoader;
import com.hangzhou.xyj.net.http.okhttp.OkHttpClientManager;
import com.hangzhou.xyj.net.request.AddDynamicReq;
import com.hangzhou.xyj.ui.activity.base.BaseActivity;
import com.hangzhou.xyj.ui.adapter.PublishImgAdapter;
import com.hangzhou.xyj.ui.dialog.TipsDialog;
import com.hangzhou.xyj.ui.widget.CommonTitleBarView;
import com.hangzhou.xyj.ui.widget.DividerGridItemDecoration;
import com.hangzhou.xyj.ui.widget.multiimageselector.MultiImageSelectorActivity;
import com.hangzhou.xyj.ui.widget.views.MyTextView;
import com.hangzhou.xyj.utils.EventBusUtil;
import com.hangzhou.xyj.utils.StringUtil;
import com.hangzhou.xyj.utils.ToastUtil;
import com.hangzhou.xyj.utils.constants.API;
import com.hangzhou.xyj.utils.constants.DataKey;

import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Request;

/**
 * Created by Administrator on 2016/1/19.
 */
public class PublishDynamicActivity extends BaseActivity {
    public static final int REQUEST_CODE_IMAGE = 1;
    RecyclerView mRecyclerView;
    PublishImgAdapter adapter;
    DividerGridItemDecoration itemDecoration;

    private String result = "";//返回结果

    private EditText mEtContent;//动态内容
    private List<String> imgList;//图片集合
    private MyTextView mTvLocation;//地点


    private String textContent;
    private String location;
    private String address;
    private int mFlagLocation = -100;//定位标志：0，正在定位；1，成功；-1，失败
    private BaiduMapLocationEngine locationEngine;


    private List<String> pathList = new ArrayList<>();//图片路径
    private List<String> serverImgPathList = new ArrayList<String>();//上传图片到服务器之后返回的路径

    private int mIntentTag;

    @Override
    public void initIntentData(Intent intent) {
        super.initIntentData(intent);
        mIntentTag = intent.getIntExtra(DataKey.INTENT_TAG, -1);
    }

    @Override
    public void initTop() {
        enableTitle(true, "发布");
        enableRightNav(true, "确定");
        setOnNavRightListener(new CommonTitleBarView.OnNavRightListener() {
            @Override
            public void onNavRight() {
                textContent = mEtContent.getText().toString().trim();
                if (StringUtil.isEmpty(textContent)) {
                    ToastUtil.show("内容不能为空");
                    return;
                }
                location = mTvLocation.getText().toString().trim();
                switch (mFlagLocation) {
                    case -1:
                    case 0://如果定位的地址没有取到，就取资料里面的城市
                        location = XYJApplication.getUserInfo().getZone();
                    case 1:
                    default:
                        break;
                }
                //弹出Loading对话框
                showLoadingDialog();
                pathList = adapter.getImageList();
                if (pathList.isEmpty()) {
                    addDynamic(textContent, address, location, null);
                }
                for (String str : pathList) {
                    uploadFile(str);
                }
            }
        });
    }

    @Override
    public void initLayouts() {
        setContentView(R.layout.activity_publish_dynamic);
    }

    @Override
    public void initViews() {
        mRecyclerView = (RecyclerView) findViewById(R.id.rv_content);
        mEtContent = (EditText) findViewById(R.id.et_content);
        mTvLocation = (MyTextView) findViewById(R.id.mtv_loaction);
    }

    @Override
    public void initDatas() {
        EventBusUtil.register(this);
        BaiduMapLocationEngine locationEngine = new BaiduMapLocationEngine(this);
        mRecyclerView.setLayoutManager(new CustomGridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        adapter = new PublishImgAdapter(this);
        itemDecoration = new DividerGridItemDecoration(this);
        mRecyclerView.addItemDecoration(itemDecoration);
        adapter.setOnItemClickListener(new PublishImgAdapter.OnItemClickListener() {
            @Override
            public void onLastItemClick(int currentSize) {
                //如果是最后一个图片并且图片小于9张，可以继续添加
                if (currentSize < 9) {
                    Intent intent = new Intent(mContext, MultiImageSelectorActivity.class);
                    // 是否显示调用相机拍照
                    intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
                    // 最大图片选择数量
                    intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 9 - currentSize);
                    // 设置模式 (支持 单选/MultiImageSelectorActivity.MODE_SINGLE 或者 多选/MultiImageSelectorActivity.MODE_MULTI)
                    intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
                    IntentManager.getInstance().goImageSelectorActivity(PublishDynamicActivity.this, intent, REQUEST_CODE_IMAGE);
                }
            }
        });
        adapter.setOnMaxItemDeleteListener(new PublishImgAdapter.OnMaxItemDeleteListener() {
            @Override
            public void OnMaxItemDelete(int maxSize) {
                mRecyclerView.getChildAt(maxSize).setVisibility(View.VISIBLE);
            }
        });
        mRecyclerView.setAdapter(adapter);
        //请求地址
        locationEngine.requestLocation();
    }

    @Override
    public void initListeners() {
        mTvLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //请求定位
                locationEngine = new BaiduMapLocationEngine(this);
                locationEngine.requestLocation();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_IMAGE && resultCode == RESULT_OK) {
            // 获取返回的图片列表
            List<String> tempList = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
//            pathList.addAll(tempList);
            for (String path : tempList) {
                ImageModel image = new ImageModel(path, System.currentTimeMillis());
                adapter.addData(image);
            }
            adapter.notifyDataSetChanged();
        }
    }

    /**
     * 单个文件上传
     *
     * @param
     * @return 返回上传到服务器以后，文件在服务器上的地址
     * @author yaohuix
     * @date 2016/3/18 13:38
     */
    public void uploadFile(final String fileName) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClientManager.getInstance().postAsyn(API.FILE_UPLOAD, new OkHttpClientManager.ResultCallback<String>() {

                        @Override
                        public void onError(Request request, Exception e) {
                            ToastUtil.show("测试：有一张上传出错！");
                            count++;
                        }

                        @Override
                        public void onResponse(String response) {
                            JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
                            boolean isSuccess = "success".equals(jsonObject.get("msg").getAsString()) ? true : false;
                            String path = jsonObject.get("data").getAsString();
                            count++;
                            if (isSuccess) {
                                serverImgPathList.add(path);
                                if (count == pathList.size()) {
                                    count = 0;//归零
                                    addDynamic(textContent, address, location, serverImgPathList);
                                }
                            }
                        }
                    }, new File(fileName), "file");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 添加动态
     *
     * @param textContent 文本内容
     * @param address     详细地址
     * @param location    城市
     * @param pathList    图片的URL地址（传到服务器返回的地址）
     * @return
     * @author yaohuix
     * @date 2016/3/18 15:32
     * <p/>
     */

    public void addDynamic(String textContent, String address, String location, List<String> pathList) {
        AddDynamicReq addDynamicReq = new AddDynamicReq(2, XYJApplication.getUserInfo().getUserId(),
                textContent, address, location, pathList);
        HttpLoader.getInstance().sendRequest(new AddDynamicHandler(addDynamicReq, new MyHttpResponseListener() {
            @Override
            public void onSuccess(Object model) {
                super.onSuccess(model);
                hideLoadingDialog();
                if (mIntentTag == EIntentTagType.TAG_MY_ACTIVE.getValue()) {
                    ToastUtil.show("动态发布成功！");
                    OperationRespEvent event = new OperationRespEvent();
                    event.setTag("MyActiveInfoActivity");
                    event.setCode(EventCode.SUCCESS);
                    EventBusUtil.postEvent(event);
                    closeActivity();
                } else {
                    TipsDialog dialog = new TipsDialog(mContext, "动态发布成功！", "可以到我的动态页面查看", "现在查看", "以后再说") {
                        @Override
                        protected void OnClickNegativeButton() {
                            PublishDynamicActivity.this.finish();
                        }

                        @Override
                        protected boolean OnClickPositiveButton() {
                            //跳转到我的动态
                            IntentManager.getInstance().goActivity(mContext, new Intent(mContext, MyActiveInfoActivity.class));
                            closeActivity();
                            return true;
                        }

                    };
                    dialog.show();
                }
            }

            @Override
            public void onError() {
                super.onError();
                hideLoadingDialog();
            }

            @Override
            public void onDone(String msg) {
                super.onDone(msg);
                hideLoadingDialog();
            }

            @Override
            public void onFail(String msg) {
                super.onFail(msg);
                hideLoadingDialog();
            }
        }, 0));
    }

    /**
     * 定位消息处理
     *
     * @param
     * @return
     * @author yaohuix
     * @date 2016/3/30 14:40
     */
    @Subscribe
    public void onEventMainThread(LocationRespEvent event) {
        switch (event.getCode()) {
            case EventCode.START:
                mTvLocation.setText("正在定位...");
                mFlagLocation = 0;
                break;
            case EventCode.SUCCESS:
                String city = event.getData().getCity();
                mTvLocation.setText(city);
                address = event.getData().getDetail();
                mFlagLocation = 1;
                break;
            case EventCode.FAIL:
                mTvLocation.setText("定位失败，点击重试!");
                mFlagLocation = -1;
                break;
        }
    }

    class CustomGridLayoutManager extends GridLayoutManager {
        public CustomGridLayoutManager(Context context, int spanCount) {
            super(context, spanCount);
        }

        public CustomGridLayoutManager(Context context, int spanCount, int orientation, boolean reverseLayout) {
            super(context, spanCount, orientation, reverseLayout);
        }

        @Override
        public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {
            try {
                //不能使用   View view = recycler.getViewForPosition(0);
                //measureChild(view, widthSpec, heightSpec);
                // int measuredHeight  view.getMeasuredHeight();  这个高度不准确
                if (adapter != null && adapter.getItemHeight() > 0) {
                    int measuredWidth = View.MeasureSpec.getSize(widthSpec);
                    int measuredHeight = adapter.getItemHeight();
                    int line = adapter.getItemCount() / getSpanCount();
                    if (adapter.getItemCount() % getSpanCount() > 0) line++;
                    setMeasuredDimension(measuredWidth, (measuredHeight + 15) * line);
                } else {
                    super.onMeasure(recycler, state, widthSpec, heightSpec);
                }

            } catch (Exception e) {
                super.onMeasure(recycler, state, widthSpec, heightSpec);
            }
        }
    }

}
